/*************************************************************
 * Title: HibernateHelper.java
 * Description: 
 * Author: Huang Shaobin
 * Email: huangshaobin@qtt.cn
 * CreateTime: Feb 6, 2013 5:10:50 PM
 * Copyright © 北京全天通信息咨询服务有限公司 All right reserved
 ************************************************************/
package snow.core.persistence.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 *
 */
public class HibernateHelper {

	private static final Log log = LogFactory.getLog(HibernateHelper.class);

	public static void closeSession(boolean participate, boolean isSingleSession, SessionFactory sessionFactory) {
		if (!participate) {
			if (isSingleSession) {
				// single session mode
				SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
				log.debug("Closing single Hibernate Session in HibernateHelper");
				closeSession(sessionHolder.getSession(), sessionFactory);
			} else {
				// deferred close mode
				SessionFactoryUtils.processDeferredClose(sessionFactory);
			}
		}
	}

	public static void closeSession(Session session, SessionFactory sessionFactory) {
		SessionFactoryUtils.closeSession(session);
	}

	public static Session getSession(SessionFactory sessionFactory, FlushMode flushMode) {
		Session session = SessionFactoryUtils.getSession(sessionFactory, true);
		if (flushMode != null) {
			session.setFlushMode(flushMode);
		}
		return session;
	}

	public static boolean openSession(boolean isSingleSession, SessionFactory sessionFactory, FlushMode flushMode) {
		boolean participate = false;
		if (isSingleSession) {
			// single session mode
			if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
				// Do not modify the Session: just set the participate flag.
				participate = true;
			} else {
				log.debug("Opening single Hibernate Session in HibernateHelper");
				Session session = getSession(sessionFactory, flushMode);
				TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
			}
		} else {
			// deferred close mode
			if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
				// Do not modify deferred close: just set the participate flag.
				participate = true;
			} else {
				SessionFactoryUtils.initDeferredClose(sessionFactory);
			}
		}
		return participate;
	}
}
